//
//  CategoryViewController.m
//  YunGou
//
//  Created by macbook on 16/5/16.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "CategoryViewController.h"
#import "GoodsDetailViewController.h"
#import "CategoryCell.h"
#import "DropTableView.h"
#import "CategoryTypeModel.h"
#import "NSObject+Tools.h"
#import "ProductModel.h"
#import <MJRefresh.h>

@interface CategoryViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet RootTableView *tableView;
@property (nonatomic,strong) DropTableView *dropTableView;
@property (nonatomic,strong) NSArray *rightTitleArray;
@property (nonatomic,strong) NSArray *rightIdArray;
@property (nonatomic,strong) NSMutableArray *goodsArray;
@property (nonatomic,strong) UIButton *currentSelectedBtn;
@property (nonatomic,assign) NSInteger page;
@end

@implementation CategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _currentSelectedBtn = nil;
    _rightTitleArray = @[@"即将揭晓",@"人气",@"价格（由高到低）",@"价格（由低到高）",@"最新"];
    _rightIdArray = @[@"1",@"2",@"3",@"4",@"5"];
    
    _page = 0;
    _goodsArray = [NSMutableArray array];
    [self loadDataWithCateId:nil sortId:nil];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _goodsArray = [NSMutableArray array];
        _page = 0;
        [self loadDataWithCateId:nil sortId:nil];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _page ++;
        [self loadDataWithCateId:nil sortId:nil];
    }];
}

- (void)loadDataWithCateId:(NSString *)cateId sortId:(NSString *)sortId{
    [MBProgressHUD showMessage:@"正在加载"];
    [NetWorkTool categoryListWithCategoryId:cateId sortId:sortId start:_page * 10 success:^(id object) {
        [MBProgressHUD hideHUD];
        if ([object[@"code"] integerValue] == 1) {
            for (NSDictionary *dict in object[@"data"]) {
                ProductModel *model = [ProductModel modelWithDict:dict];
                [_goodsArray addObject:model];
            }
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

//头部点击事件
- (IBAction)headBtnClicked:(UIButton *)sender {
    if (_currentSelectedBtn == nil) {
        _currentSelectedBtn = sender;
        sender.selected = YES;
        [self.view addSubview:self.dropTableView];
        [self loadHeadCategoryWithBtn:sender];
    }else{
        if (_currentSelectedBtn == sender) {
            [self.dropTableView removeFromSuperview];
            self.dropTableView = nil;
            _currentSelectedBtn = nil;
            sender.selected = NO;
            return;
        }
        _currentSelectedBtn.selected = NO;
        _currentSelectedBtn = sender;
        sender.selected = YES;
        [self loadHeadCategoryWithBtn:sender];
    }
}

- (void)loadHeadCategoryWithBtn:(UIButton *)sender{
    NSMutableArray *categoryArray = [NSMutableArray array];
    
    if (sender.tag == 1) {
        CategoryTypeModel *allTypeModel = [CategoryTypeModel new];
        allTypeModel.cateid = NULL;
        allTypeModel.name = @"全部商品";
        [categoryArray addObject:allTypeModel];
        [NetWorkTool categoryTypeWithSuccess:^(id object) {
            if ([object[@"code"] integerValue] == 1) {
                for (NSDictionary *dict in object[@"data"]) {
                    CategoryTypeModel *categoryTypeModel = [CategoryTypeModel modelWithDict:dict];
                    [categoryArray addObject:categoryTypeModel];
                }
            }
            self.dropTableView.categoryTypeArray = categoryArray;
            [self.dropTableView reloadData];
        } failure:^(NSError *error) {
            
        }];
    }else{
        for (NSInteger i = 0; i < _rightIdArray.count; i ++) {
            CategoryTypeModel *model = [CategoryTypeModel new];
            model.cateid = _rightIdArray[i];
            model.name = _rightTitleArray[i];
            [categoryArray addObject:model];
        }
        self.dropTableView.categoryTypeArray = categoryArray;
        [self.dropTableView reloadData];
    }
}

//下拉列表懒加载
- (DropTableView *)dropTableView{
    if (!_dropTableView) {
        _dropTableView = [[DropTableView alloc] initWithFrame:CGRectMake(0, 40, ScreenWidth, ScreenHeight - 44 - 64 - 49)];
        __weak typeof(self) ws = self;
        _dropTableView.dropTableViewBlock = ^(NSInteger row){
            CategoryTypeModel *model = ws.dropTableView.categoryTypeArray[row];
            ws.currentSelectedBtn.selected = NO;
            if (_currentSelectedBtn.tag == 1) {
                _page = 0;
                _goodsArray = [NSMutableArray array];
                [ws loadDataWithCateId:model.cateid sortId:nil];
                ws.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                    ws.page = 0;
                    [ws loadDataWithCateId:model.cateid sortId:nil];
                }];

                ws.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                    ws.page ++;
                    [ws loadDataWithCateId:model.cateid sortId:nil];
                }];
            }else{
                _page = 0;
                _goodsArray = [NSMutableArray array];
                [ws loadDataWithCateId:nil sortId:model.cateid];
                ws.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                    ws.page = 0;
                    [ws loadDataWithCateId:nil sortId:model.cateid];

                }];

                ws.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                    ws.page ++;
                    [ws loadDataWithCateId:nil sortId:model.cateid];
                }];
            }
            _currentSelectedBtn = nil;
            [ws.dropTableView removeFromSuperview];
            ws.dropTableView = nil;
        };
        UIView *footerView = [UIView new];
        _dropTableView.tableFooterView = footerView;
    }
    return _dropTableView;
}

#pragma -mark tableView delegate and dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _goodsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"categoryCell"];
    ProductModel *productModel = _goodsArray[indexPath.row];
    cell.block = ^{
        [NetWorkTool addShopCartWithGoodsId:productModel.Id success:^(id object) {
            if ([object[@"code"] integerValue] == 1) {
                [MBProgressHUD showSuccess:@"添加成功"];
            }
        } failure:^(NSError *error) {
        }];
    };
    cell.productModel = productModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GoodsDetailViewController *goodsDetailVC = SB(@"Common", @"GoodsDetailVC");
    goodsDetailVC.productModel = _goodsArray[indexPath.row];
    goodsDetailVC.detailType = DonotAnnounce;
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}

@end
